import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:syria_sports/core/app_export.dart';
import 'package:syria_sports/core/utils/show_toast.dart';
import 'package:syria_sports/data/apiClient/apis_data.dart';
import 'package:syria_sports/data/controllers/cp_controller.dart';
import 'package:syria_sports/data/controllers/subscriptions_controller.dart';
import 'package:syria_sports/presentation/admin_home_tabs/cp_tab/models/home_model.dart';

part 'cp_state.dart';

class CPCubit extends Cubit<CPState> {
  CPCubit() : super(CPInitial());

  static CPCubit get(context) => BlocProvider.of(context);

  late HomeModel homeData;


  void init(bool isOnline) {
    if(isOnline) {
      getHomeData();
      checkUserSubscription();
    }else{
      getOfflineHomeData();
    }

  }

  getOfflineHomeData(){
    var res = PrefUtils.getHomeData();
    if(res != null){
      homeData =res;
      APISData.homeData = homeData;
      emit(CPDone());
    }else{
      emit(CPError());
    }
  }

  getHomeData()async{
    emit(CPLoading());
    await CPController.getHomeData().then((value){
      if(value == null){
        debugPrint('home controller return null!!');
        showErrorMessage(message: 'حدث خطأ الرجاء إعادة المحاولة لاحقاً');
        emit(CPError());
        return ;
      }
      PrefUtils.saveHomeData(json.encode(value.data));
      homeData =HomeModel.fromJson(value.data);
      APISData.homeData = homeData;
      emit(CPDone());
    });
  }

  selectExercise(String exerciseId){
    CPController.selectExercise(exerciseId).then((value) {
      getHomeData();
    }).catchError((e){
      showErrorMessage(message: 'عذراً حدث خطأ ما الرجاء إعادة المحاولة لاحقاً');
    });
  }


  checkUserSubscription(){
    SubscriptionsController.check();
  }

}
